SUIPatternLibrary.TemplateManager = (function($, _){
    
    var observable = {},
    
    templates = {
        "tabview" : undefined,
        "accordion-section" : undefined,
        "overlay" : undefined,
        "pattern-detail" : undefined,
        "pattern-list-item" : undefined
    },
    
    init = function(){
        for(var id in templates){
            fetchTemplate(id);
        }
    },
    
    wait = function(millis) {
        var date = Date.now();
        var curDate = null;
        do { curDate = Date.now(); } 
        while(curDate-date < millis);
    },
    
    fetchTemplate = function(id){
        $.get("chrome-extension://kekdndmjncddhhipkdfmlfgcppphkdke/templates/" + id + ".html", "", function(html){
            templates[id] = _.template(html);
            if(templatesLoaded()){
                $(observable).trigger("ready");
            }
        });
    },
   
    templatesLoaded = function(){
        for(var id in templates){
            if(templates[id] == undefined) return false;            
        };
        return true;
    },
   
    ready = function(callback){
        $(observable).on("ready", callback);
    },
   
    compileTemplate = function(id, data){
        if(!templatesLoaded()){
            wait(100);
            return compileTemplate(id, data);
        }
        return ($(templates[id](data)));
    };
    
    return {
        init : init,
        ready : ready,
        compileTemplate: compileTemplate
    }
    
}(jQuery, _));